#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QCameraFormat>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_camera = new QCamera(QMediaDevices::defaultVideoInput());
    m_captureSession.setCamera(m_camera);

    m_captureSession.setVideoSink(&m_videoSink);
    connect(&m_videoSink, &QVideoSink::videoFrameChanged, this, &MainWindow::on_frame_changed);

    m_camera->start();
    m_file.setFileName("test.nv12");
    m_file.open(QIODevice::WriteOnly | QIODevice::Truncate);
}

MainWindow::~MainWindow()
{
    m_camera->stop();
    m_file.close();

    delete ui;
}

void MainWindow::on_frame_changed(const QVideoFrame &frame)
{
    QVideoFrame videoFrame = frame;
    /**
     * 我的电脑上返回的格式是Format_NV12：18，每个像素1.5字节，一帧1382400字节，
     * 如果你需要用别的YUV或者RGB格式，则需要自己设置QVideoSink或者QCamera格式
     */
    QVideoFrameFormat::PixelFormat pixelFormat = videoFrame.pixelFormat();
    int width = videoFrame.width();
    int height = videoFrame.height();
    int planeCount = videoFrame.planeCount();
    uchar *pdata = nullptr;
    int len = 0;

    videoFrame.map(QVideoFrame::ReadOnly);

    for (int i = 0; i < planeCount; i++) {
        pdata = videoFrame.bits(i);
        len = videoFrame.mappedBytes(i);
        m_file.write((const char *)pdata, len);
    }

    frame_num++;
    qDebug("%d, %d, %d, %d, %d, %p, %d", frame_num,
           pixelFormat, width, height, planeCount, pdata, len);

    videoFrame.unmap();
}
